package com.flycms.modules.system.controller;

import com.flycms.common.constant.UserConstants;
import com.flycms.common.controller.BaseController;
import com.flycms.modules.shiro.ShiroUtils;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Biz-Boot, All rights reserved
 * 版权：企业之家网 -- 企业建站管理系统<br/>
 * 开发公司：97560.com<br/>
 *
 * 图片验证码（支持算术形式）
 * 
 * @author 孙开飞
 */
@Controller
@RequestMapping("/captcha")
public class CaptchaController extends BaseController
{
    @Autowired
    private Producer producer;

    /**
     * 生成验证码
     * @param response
     * @throws IOException
     */
    @RequestMapping("/captcha{url.suffix}")
    public void captcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    @RequestMapping("/validateCode{url.suffix}")
    public void validateCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        int width = 126;
        int height = 48;
        int fontHeight = 32;

        // 定义图像buffer-画布
        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //创建2D画笔
        Graphics2D g = buffImg.createGraphics();

        // 将图像填充为白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 创建字体，字体的大小应该根据图片的高度来定。
        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
        // 设置字体。
        g.setFont(font);

        // 画边框。
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);

        // 随机产生干扰线
        g.setColor(Color.BLACK);
        Random random = new Random();
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(20);
            int yl = random.nextInt(20);
            g.drawLine(x, y, x + xl, y + yl);
        }

        //randomCode-用于保存随机产生的验证码,即画布上面的图画
        String randomCode = "";
        int validateCode = 0;

        /**
         * 加减数字控制在10以内
         */
        int a = random.nextInt(4) + 5;
        int b = random.nextInt(4);

        //随机加减乘,除法要处理意外，忽略
        int c = random.nextInt(3);
        switch (c) {
            case 0:
                randomCode = a + "加" + b + "=?";
                validateCode = a + b;
                break;
            case 1:
                randomCode = a + "减" + b + "=?";
                validateCode = a - b;
                break;
            case 2:
                randomCode = a + "乘" + b + "=?";
                validateCode = a * b;
                break;
            default:
                break;
        }

        int red = random.nextInt(255);
        int green = random.nextInt(255);
        int blue = random.nextInt(255);

        // 用随机产生的颜色将验证码绘制到图像中。
        g.setColor(new Color(red, green, blue));
        g.drawString(randomCode, 10, 35);

        //保存session,用于登录验证
        request.getSession().setAttribute(UserConstants.KAPTCHA_SESSION_KEY, validateCode);

        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //将图像输出->流打印
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(buffImg, "jpeg", sos);
        sos.close();
    }
}